<template>
  <view class="safe-area-inset-bottom">
    <view class="swip_header">
      <view class="slot-box">
        <view style="width: 100%;">
          <uni-search-bar
              v-model="queryParams.number"
              type="text"
              @confirm="handleQuery"
              @input="handleQuery"
              placeholder="请输入订单号"/>
        </view>
      </view>
    </view>

    <!-- 列表 -->
    <view class="listSearchTop" v-if="dataList != ''">
      <uni-card :is-shadow="false" v-for="(item,index) in dataList" :key="index">
        <view class="flex_between">
          <p class="grid-integral">充值单号：{{ item.number }}</p>
          <!-- 订单状态 -->
          <template v-for="(dictItem, index) in dicts.ec_order_status">
            <template v-if="item.status == dictItem.value">
              <uni-tag :text="dictItem.text" size="small" :type="dictItem.type"/>
            </template>
          </template>
        </view>
        <p class="grid-integral">充值金额(元)：{{ item.amount }}元</p>
        <p class="grid-integral">可用金额(元)：{{ item.availableBalance }}元</p>
        <p class="grid-integral">充值渠道：
          <template v-for="(dictItem, index) in dicts.ec_trading_channel">
            <template v-if="item.channel == dictItem.value">
              <uni-tag :text="dictItem.text" size="small" :type="dictItem.type"/>
            </template>
          </template>
        </p>
        <p class="grid-integral">交易单号：
          <span v-if="!!item.transactionId">{{ item.transactionId }}</span>
          <span v-else>--</span>
        </p>
        <p class="grid-integral">创建时间：
          <span v-if="!!item.createTime">{{ item.createTime }}</span>
          <span v-else>--</span>
        </p>
        <p class="grid-integral">充值时间：
          <span v-if="!!item.successTime">{{ item.successTime }}</span>
          <span v-else>--</span>
        </p>
        <view slot="actions" class="card-actions" v-if="item.status == 0 || item.status == 1 || item.status == 5">
          <view></view>
          <view class="flex_between">
            <view class="card-actions-item" @click="handleView(item)"
                  v-if="item.status == 1 && item.availableBalance > 0">
              <text class="card-actions-item-text errorColor">原路退款</text>
            </view>
            <view class="card-actions-item" @click="continuePay(item)" v-if="item.status == 0">
              <text class="card-actions-item-text themeColor">继续充值</text>
            </view>
            <view class="card-actions-item" @click="handleDelete(item,index)" v-if="item.status == 5">
              <text class="card-actions-item-text errorColor">删除</text>
            </view>
          </view>
        </view>
      </uni-card>
      <!-- 加载更多 -->
      <uni-load-more color="#00a660" :status="loadStatus"/>
    </view>
    <!-- 暂无数据 -->
    <luanqingEmpty :show="true" text="没有更多数据啦" v-else/>
    <!--充值 原路返回-->
    <refund-original ref="refundOriginal" @success="handleQuery"/>
  </view>
</template>

<script>
import {delBalancePay, listBalancePay} from "@/api/ec/person/fee/ecAccountBalancePay";
import luanqingEmpty from '@/components/luanqing-empty/luanqing-empty';
import {getDictsByNameForUni} from "@/utils/dicts";
import {isWebView, isWechat} from "../../../../../utils/validate";
import refundOriginal from "./refundOriginal";

export default {
  components: {luanqingEmpty, refundOriginal},
  data() {
    return {
      // 数据字典
      dicts: {
        // 充值渠道
        ec_trading_channel: [],
        // 订单支付状态
        ec_order_status: [],
      },
      // 加载样式：more-加载前样式，loading-加载中样式，nomore-没有数据样式
      loadStatus: 'loading',
      // 数据列表
      dataList: [],
      //总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inOutType: null,
        channel: null,
        params: {
          findApi: undefined
        }
      },
    }
  },
  onLoad(option) {
    this.getDicts()
  },
  created() {
    this.getList();
  },
  /** 上拉刷新回调 */
  onReachBottom() {
    if (this.loadStatus != 'noMore' && this.total > this.dataList.length) {
      this.loadStatus = 'loading';
      // 延迟500毫秒显示loading效果
      setTimeout(() => {
        // 执行查询的方法
        this.getList(false);
      }, 500)
    } else {
      // 停止加载
      this.loadStatus = 'noMore'
    }
  },
  methods: {
    /**加载数据字典*/
    getDicts() {
      // 充值渠道
      this.dicts.ec_trading_channel = getDictsByNameForUni("ec_trading_channel");
      // 订单支付状态
      this.dicts.ec_order_status = getDictsByNameForUni("ec_order_status");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList(true);
    },
    /** 列表查询 */
    getList(reload) {
      if (reload) {
        this.queryParams.pageNum = 1;
        this.loadStatus = 'more'
        this.$modal.loading();
      }
      listBalancePay(this.queryParams).then(response => {
        if (reload) {
          uni.hideLoading()
        }
        this.total = response.total;
        if (response.total > 0) {
          const dataRows = response.rows;
          this.dataList = reload ? dataRows : this.dataList.concat(dataRows);
        } else {
          this.dataList = [];
        }
        // 判断数据是否加载完全
        if (response.total <= this.dataList.length) {
          this.loadStatus = 'noMore'
        }
        // 页数+1
        this.queryParams.pageNum++
      }).catch(() => {
        if (reload) {
          uni.hideLoading()
        }
      });
    },
    /** 原路退款 */
    handleView(item) {
      // uni.navigateTo({url: './originalRefund?id=' + item.id});
      this.$refs.refundOriginal.toOpenDialog(item);
    },
    /** 继续充值 */
    continuePay(item) {
      if (navigator.vibrate) {
        navigator.vibrate(50);
      }
      //扫码继续
      if (item.subChannel == 1) {
        this.$modal.msgError("请回电脑端继续扫码支付");
        return;
      }
      //校验环境
      if (isWebView()) {
        // TODO 小程序环境
        return;
      } else if (isWechat()) { // 微信浏览器环境
        if (item.subChannel == 2) {// 不是jsapi参数
          this.$modal.msgError("请用外部浏览器,继续支付");
          return;
        }
      } else {
        // h5环境 参数是jsapi
        if (item.subChannel == 3) {
          this.$modal.msgError("请用微信内置浏览器,继续支付");
          return;
        }
      }
      // h5继续充值
      if (item.subChannel == 2) {
        window.location.href = item.codeUrl;
      }
      //jsapi继续充值
      if (item.subChannel == 3) {
        let data = JSON.parse(item.codeUrl);
        WeixinJSBridge.invoke('getBrandWCPayRequest', {
          "appId": data.appId,     //公众号ID，由商户传入
          "timeStamp": data.timeStamp,     //时间戳，自1970年以来的秒数
          "nonceStr": data.nonceStr,      //随机串
          "package": data.prepayId,
          "signType": "RSA",     //微信签名方式：
          "paySign": data.paySign //微信签名
        }, res => {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            this.$modal.msgSuccess("支付完成");
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          }
        });
      }
    },
    /** 删除 */
    handleDelete(item, index) {
      let that = this
      uni.showModal({
        title: '系统提示',
        content: '您确认要删除充值记录吗？删除后将无法恢复。',
        confirmColor: '#00a660',
        success: function (res) {
          if (res.confirm) {
            const id = item.id;
            delBalancePay(id).then(() => {
              that.dataList.splice(index, 1)
              that.$modal.msgSuccess("删除成功");
            });
          }
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">
::v-deep .uni-card .uni-card__content {
  padding: 20rpx 20rpx 0 20rpx;
}

page {
  background: $uni-bg-color-grey;
}
</style>
